//
//  BookSelectSheetView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 26.03.25.
//

import SwiftUI

struct BookSelectSheetView: View {
    
    @Environment(\.presentationMode) var presentationMode
    
    var selectedBookId: String
    
    var onSelectedBook:(AccountingBook) -> Void
    
    var onAddBook:() -> Void
    
    @StateObject var viewModel = BookSelectSheetViewModel()
    
    @State private var contentHeight: CGFloat = .zero
    // 最小高度常量
    private let minimumHeight: CGFloat = 100
    // 最大高度比例
    private let maxHeightRatio: CGFloat = 0.9
    
    private var calculatedHeight: CGFloat {
        // 计算最终高度，考虑最小值和最大值
        let maxHeight = UIScreen.main.bounds.height * maxHeightRatio
        return min(
            max(contentHeight + 32, minimumHeight),
            maxHeight
        )
    }
    
    private var heightReader: some View {
        GeometryReader { geometry in
            Color.clear.preference(
                key: ContentHeightPreferenceKey.self,
                value: geometry.size.height
            )
        }
        .onPreferenceChange(ContentHeightPreferenceKey.self) { height in
            // 使用 withAnimation 使高度变化更平滑
            withAnimation(.easeInOut(duration: 0.25)) {
                contentHeight = height
            }
        }
    }
    
    var body: some View {
        GeometryReader { geometry in
            VStack {
                Text("选择账本")
                    .font(.system(size: 16))
                    .bold()
                    .foregroundColor(Color.koiColorTitle)
                    .padding(.bottom, 10)
                    .padding(.top, 20)
                ScrollView {
                    LazyVStack {
                        ForEach($viewModel.books) { item in
                            Button(action:{
                                onSelectedBook(item.wrappedValue)
                                presentationMode.wrappedValue.dismiss()
                            }) {
                                BookItemView(book: item.wrappedValue, isSelected: item.wrappedValue.bookId == selectedBookId)
                                    .padding(EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10))
                            }
                        }
                        Color.clear.frame(height: 30)
                    }
                    .onReceive(viewModel.$books) { newValue in
//                        print("onReceive ",newValue)
                    }
                    .padding()
                    .background(heightReader)
                }
                .frame(maxWidth: .infinity)
            }.onAppear {
                viewModel.loadBooks()
            }
        }.presentationDetents([.height(calculatedHeight)])
        .task {
            await loadData()
        }
    }
    
    private func loadData() async {
        viewModel.loadBooks()
    }
}


// 定义高度 PreferenceKey
struct ContentHeightPreferenceKey: PreferenceKey {
    static var defaultValue: CGFloat = .zero
    
    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = nextValue()
    }
}

@available(iOS 18.0, *)
#Preview {
    @Previewable @State var selectedBookId = ""
    BookSelectSheetView(selectedBookId: selectedBookId, onSelectedBook: { _ in }, onAddBook: {})
}
